import io from 'socket.io-client'
import { Toast } from 'antd-mobile'
import {
    registerReq,
    loginReq,
    updateUserReq,
    getUserReq,
    userListReq,
    getChatMsgListReq,
    readMsgReq
} from '../api'

import {
    AUTH_SUCCESS,
    ERROR_MSG,
    UPDATE_USER_SUCCESS,
    UPDATE_USER_FAILED,
    GET_USER_SUCCESS,
    GET_USER_FAILED,
    RECEIVE_USER_LIST,
    RECEIVE_MSG,
    RECEIVE_CHAT_MSG_LIST,
    RECEIVE_READ_MSG
} from './action-type'

function initIO(dispatch,userId) {
    if(!io.socket){
        io.socket = io.connect('ws://localhost:4000')
        io.socket.on('receiveMsg',function (data) {
            console.log('receiveMsg',data)
            if (data.from === userId || data.to === userId ) {
                dispatch(receiveMsg(data,userId))
            }
        })
        io.socket.on('receiveLogout',function (data) {
            console.log('receiveMsg',data)
        })
    }
}

export const logout = () =>{
    return async dispatch =>{
        io.socket.emit('logout')
        io.socket = null
    }
}

async function getChatMsgList(dispatch,userId) {
    initIO(dispatch,userId)
    const result = await getChatMsgListReq()
    if (result.status === 1){
        const { users, chatMsgs } = result.data
        dispatch(receiveChatMsgList({ users, chatMsgs, userId }))
    }
}

export const sendMsg = ({ from,to,content }) =>{
    console.log('sendMsg',{ from,to,content })
    return async dispatch =>{
        io.socket.emit('sendMsg',{ from,to,content })
    }

}


const msgRead = (count,from,to) => ({ type:RECEIVE_READ_MSG,data: { count,from,to } })
const authSuccess = (user) => ({ type:AUTH_SUCCESS, data:user })
const errorMsg = (msg) => ({ type: ERROR_MSG, data: msg })
const updateUserSuccess = (user) => ({ type:UPDATE_USER_SUCCESS,data:user })
export const resetUser = (msg) => ({ type: UPDATE_USER_FAILED,data:msg})

const getUserSuccess = (user) => ({ type:GET_USER_SUCCESS,data:user })
const getUserFailed = (msg) => ({ type: GET_USER_FAILED,data:msg})

const receiveUserList = (userList) => ({ type:RECEIVE_USER_LIST,data:userList})
const receiveChatMsgList = ({ users, chatMsgs,userId }) => ({ type: RECEIVE_CHAT_MSG_LIST, data:{ users, chatMsgs,userId } })
const receiveMsg = (msg,userId) => ({ type:RECEIVE_MSG, data:{ msg, userId } })


export const readMsg = (targetId,userId) =>{
    return async dispatch =>{
        const result = await readMsgReq(targetId)
        if (result.status === 1){
            const count = result.data
            const from = targetId
            const to = userId
            dispatch(msgRead(count,from,to))
        }
    }
}

export const register = (user) =>{
    return async dispatch =>{
        const result = await registerReq(user)
        if (result.status === 1){
            getChatMsgList(dispatch,result.data._id)
            dispatch(authSuccess(result.data))
        } else {
            Toast.fail(result.msg, 1 )
            dispatch(errorMsg( result.msg ))
        }

    }
}

export const login = (username,password) =>{
    return async dispatch =>{
        const result = await loginReq(username,password)
        if (result.status === 1){
            getChatMsgList(dispatch,result.data._id)
            dispatch(authSuccess(result.data))
        } else {
            Toast.fail(result.msg, 1 )
            dispatch(errorMsg({ msg:result.msg }))
        }

    }
}

export const update = (user) =>{
    return async dispatch =>{
        const result = await updateUserReq(user)
        if (result.status === 1){
            dispatch(updateUserSuccess(result.data))
        } else {
            dispatch(resetUser({ msg:result.msg }))
        }
    }
}

export const getUser = () =>{
    return async dispatch =>{
        const result = await getUserReq()
        if (result.status === 1) {
            getChatMsgList(dispatch,result.data._id)
            dispatch(getUserSuccess(result.data))
        } else {
            dispatch(getUserFailed({msg:result.msg}))
        }
    }
}

export const getUserList = (userType) => {
    return async dispatch =>{
        const result = await userListReq(userType)
        if (result.status === 1){
            dispatch(receiveUserList(result.data))
        }
    }
}
